import styles from './index.module.scss';
import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import {
  clearArticleDetailByIdAction,
  getArticleDetailByIdAction,
} from '@/store/action/article';
import { useParams } from 'react-router-dom';
import { useAppSelector } from '@/store';
import dayjs from 'dayjs';
import { sanitize } from 'dompurify';
import Skeleton from '@/components/Skeleton';
import h1js from 'highlight.js';
import 'highlight.js/styles/vs2015.css';
import classnames from 'classnames';
import NoComment from './components/NoComment';
import CommentItem from './components/CommentItem';
import { clearCommentsAction, getCommentList } from '@/store/action/comment';
import CommentFooter from './components/CommentFooter';
import { Popup } from 'antd-mobile';
import CommentReply from './components/CommentReply';

// 处理日期格式
// 处理xss攻击
// 配置相对插件与中文包
// 卸载组件时清除请求数据
// ！非空断言,getBoundingClientRect相对视口距离
export default function Article() {
  const { id } = useParams<{ id: string }>();
  const { detail } = useAppSelector((state) => state.article);
  // 吸顶
  const [navAuthShow, setNavAuthShow] = useState(false); //互s
  const wrapperRef = useRef<HTMLDivElement>(null);
  const authorRef = useRef<HTMLDivElement>(null);
  const { comments, originComment } = useAppSelector((state) => state.comment);
  const { results: commentList } = comments;

  const dispatch = useDispatch();
  // 忽略未转义的html，就是富文本里面的标签可能也包含，就不用转义，直接当字符串就行

  const ScrollFn = () => {
    const top = authorRef.current!.getBoundingClientRect().top;
    // console.log(1);
    top < 10 ? setNavAuthShow(true) : setNavAuthShow(false);
  };
  useEffect(() => {
    dispatch(getArticleDetailByIdAction(id));
  }, [id, dispatch]);
  useEffect(() => {
    if (!detail.art_id) return;
    h1js.configure({
      // 忽略未经转义的 HTML 字符
      ignoreUnescapedHTML: true,
    });
    // 获取到渲染正文的容器元素
    // 查找容器元素下符合 pre code 选择器规则的子元素，进行高亮

    const codes = document.querySelectorAll('.dg-html pre code');
    if (codes.length > 0) {
      return codes.forEach((item) => h1js.highlightElement(item as any));
    }
    // 后台的code没有存在，再加个判断
    const pre = document.querySelectorAll('.dg-html pre');
    if (pre.length > 0) {
      return pre.forEach((item) => h1js.highlightElement(item as any));
    }
    // 绑定事件
  }, [detail.art_id]); //等数据回来之后再判断

  // 获取数据并且渲染

  useEffect(() => {
    if (!detail.art_id) return;
    // 移除事件
    wrapperRef.current?.addEventListener('scroll', ScrollFn);
    //
  }, [detail.art_id]);

  useEffect(() => {
    // if (!detail.art_id) return;
    // 移除事件
    dispatch(clearArticleDetailByIdAction());
    dispatch(clearCommentsAction());
    wrapperRef.current?.removeEventListener('scroll', ScrollFn);

    //
  }, [dispatch]);
  // 获取评论列表
  useEffect(() => {
    dispatch(getCommentList({ type: 'a', source: id }));
  }, [id, dispatch]);

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        {/* 顶部导航栏 */}
        <NavBar right={<Icon type="icongengduo" />}>
          {navAuthShow && (
            <div className="nav-author">
              <img src={detail.aut_photo} alt="" />
              <span className="name">{detail.aut_name}</span>
              <span
                className={classnames(
                  'follow',
                  detail.is_followed ? 'followed' : ''
                )}
              >
                {detail.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {!detail.title ? (
          <Skeleton></Skeleton>
        ) : (
          <div className="wrapper" ref={wrapperRef}>
            <div className="article-wrapper">
              {/* 文章描述信息栏 */}
              <div className="header">
                <h1 className="title">{detail.title}</h1>

                <div className="info">
                  <span>{dayjs(detail.pubdate).format('YYYY-MM-DD')}</span>
                  <span>{detail.read_count} 阅读</span>
                  <span>{detail.comm_count} 评论</span>
                </div>

                <div className="author" ref={authorRef}>
                  <img src={detail.aut_photo || ''} alt="" />
                  <span className="name">{detail.aut_name}</span>
                  <span className="follow">
                    {detail.is_followed ? '已关注' : '关注'}
                  </span>
                </div>
              </div>

              {/* 文章正文内容区域 */}
              <div className="content">
                {/* 渲染富文本框内容 */}
                <div
                  className="content-html dg-html"
                  dangerouslySetInnerHTML={{ __html: sanitize(detail.content) }}
                ></div>
                <div className="date">
                  发布文章时间：{dayjs().from(detail.pubdate)}
                </div>
                {/* 评论 */}
                <div className="divider"></div>
                <div className="comment">
                  {/* 评论总览信息 */}
                  <div className="comment-header">
                    <span>全部评论（{detail.comm_count}）</span>
                    <span>{detail.like_count} 点赞</span>
                  </div>
                  {/* 评论列表 */}
                  {detail.comm_count === 0 ? (
                    <NoComment />
                  ) : (
                    <div className="comment-list">
                      {commentList.map((item) => {
                        return <CommentItem comment={item} key={item.com_id} />;
                      })}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        )}
        <CommentFooter></CommentFooter>
        <Popup visible={!!originComment.com_id} position="right">
          <CommentReply></CommentReply>
        </Popup>
      </div>
    </div>
  );
}
